﻿using System;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using Isis.Extensions;
using Isis.Helpers.Impl;
using Isis.Model;
using Isis.Views;

namespace Isis.Controllers
{
    public class ApplicationController : ControllerBase
    {
        private readonly string _basePath;

        public ApplicationController(string basePath)
        {
            _basePath = basePath;
        }

        public override ControllerTab Tab
        {
            get { return new ControllerTab("Application"); }
        }

        public override void Render(TextWriter writer)
        {
            var pageLayoutWriter = new PageLayoutWriter(Tab.Title, Action, new ControllerRepository(), _basePath);
            pageLayoutWriter.RenderPage(writer, RenderContent);
        }

        private void RenderContent(TextWriter writer)
        {
            RenderApplicationInfoTable(writer);
        }

        private void RenderApplicationInfoTable(TextWriter writer)
        {
            var fileHelper = new ApplicationDataHelper();
            var tableHelper = new TableRenderingHelper();
            var sb = new StringBuilder();

            try
            {
                var keys = HttpContext.Current.Application.AllKeys;

                if (keys.Any())
                {
                    sb.Append(tableHelper.RenderTableHeader("HttpContext Application Records"));
                    sb.Append(tableHelper.RenderHeaderRow(new[] { "Key", "Size", "Value" }));

                    foreach (string key in keys)
                    {
                        var objectValue = HttpContext.Current.Application[key];
                        string size = "N/A - Not Serializable";
                        string output = objectValue.ToString();
                        if (objectValue.GetType().IsSerializable)
                        {
                            size = Convert.ToDouble(objectValue.GetObjectSize())/Convert.ToDouble(1000) + " KB";
                            output = objectValue.ToXml();
                        }
                        sb.AppendLine(
                            tableHelper.RenderRow(new[]
                                                      {
                                                          key,
                                                          size,
                                                          output
                                                       }));
                    }

                    sb.Append("</table>");
                }
            }
            catch (Exception)
            {
                writer.Write("<p>Application Data Unavailable</p>");
                throw;
            }

            writer.Write(sb.ToString());
        }
    }

    internal class ApplicationDataHelper
    {
    }
}